<template>
  <div>
    <!--  添加|修改  授课班级弹窗  -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="openType == 2 ? '编辑授课班级' : '添加授课班级'"
      :visible="dialogVisible"
      width="580px"
      @close="handleClose"
      @closed="clearFormValidation"
    >
      <div class="form">
        <div class="course_name">
          《
          <div style="max-width: 460px">
            <tooltip
              position="top"
              :text="courseInfo.courseName"
              width="100%"
            />
          </div>
          》
        </div>
        <div class="title">基础信息</div>
        <el-form
          :model="formSemester"
          :rules="rules"
          ref="semesterForm"
          label-width="135px"
          class="demo-ruleForm"
        >
          <el-form-item label="" prop="teacherIds" ref="teacherIds">
            <template #label>
              授课教师
              <el-tooltip class="item" effect="dark" placement="top">
                <i class="el-icon-question shou"></i>
                <div slot="content">
                  <div>拥有当前授课班级管理及对学生打分权限</div>
                </div>
              </el-tooltip>
            </template>
            <el-select
              filterable
              class="param_ipt"
              multiple
              collapse-tags
              placeholder="可搜索：请选择授课教师"
              v-model="formSemester.teacherIds"
            >
              <el-option
                v-for="(item, index) in instructorTeacherList"
                :key="index"
                :label="item.name"
                :value="item.teacherId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="assistantIds">
            <template #label>
              助教
              <el-tooltip class="item" effect="dark" placement="top">
                <i class="el-icon-question shou"></i>
                <div slot="content">
                  <div>仅拥有对当前授课班级学生打分权限</div>
                  <div>注：多角色账号可通过“角色切换”使用助教功能</div>
                </div>
              </el-tooltip>
            </template>
            <el-select
              filterable
              class="param_ipt"
              multiple
              collapse-tags
              placeholder="可搜索：可选择教师/学生账号"
              v-model="formSemester.assistantIds"
            >
              <el-option
                :disabled="addedUserId.includes(item.userId)"
                v-for="(item, index) in assistantList"
                :key="index"
                :label="item.labelName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="" prop="schedulingType" ref="schedulingType">
            <template #label>
              班级类型
              <el-tooltip class="item" effect="dark" placement="top">
                <i class="el-icon-question shou"></i>
                <div slot="content">
                  <div>
                    单独班：由单个行政班组成，会根据行政班人员变动同步更新；
                  </div>
                  <div>
                    合班：由多个行政班组成，会根据行政班人员变动同步更新；
                  </div>
                  <div>拆班：由学生组成，行政班人员变动不产生影响</div>
                  <div>注：创建班级后，班级类型不可修改，请谨慎处理</div>
                </div>
              </el-tooltip>
            </template>
            <el-radio-group
              v-removeAriaHidden
              :disabled="openType == 2"
              class="radio_group"
              v-model="formSemester.schedulingType"
            >
              <el-radio :label="0">单独班</el-radio>
              <el-radio :label="1">合班</el-radio>
              <el-radio :label="2">拆班</el-radio>
            </el-radio-group>
            <div class="sign">注：创建班级后，班级类型不可修改，请谨慎处理</div>
          </el-form-item>
          <el-form-item
            ref="schedulingName"
            v-if="formSemester.schedulingType == 2"
            label="拆班名称"
            prop="schedulingName"
          >
            <el-input
              maxlength="20"
              show-word-limit
              class="param_ipt"
              @blur="handleBlur"
              v-model="formSemester.schedulingName"
              placeholder="请输入拆班名称"
              clearable
            />
          </el-form-item>
          <el-form-item
            ref="classId"
            v-if="formSemester.schedulingType == '0'"
            label="授课班级"
            prop="classId"
          >
            <el-cascader
              filterable
              collapse-tags
              class="param_ipt"
              v-model="formSemester.classId"
              placeholder="可搜索：分院/专业/班级"
              :options="classTeachingList"
              clearable
              :props="{
                multiple: false,
                label: 'name',
                value: 'id',
                children: 'children',
                disabled: 'disabled',
              }"
            >
              <div slot="empty" class="search_empty">
                搜索班级已添加或不存在
              </div>
            </el-cascader>
          </el-form-item>
          <el-form-item
            ref="classIds"
            v-if="formSemester.schedulingType == 1"
            label="授课班级"
            prop="classIds"
          >
            <el-cascader
              filterable
              collapse-tags
              class="param_ipt"
              v-model="formSemester.classIds"
              placeholder="可搜索：分院/专业/班级"
              :options="classTeachingList"
              clearable
              :props="{
                multiple: true,
                label: 'name',
                value: 'id',
                children: 'children',
                disabled: 'disabled',
              }"
            >
              <div slot="empty" class="search_empty">
                搜索班级已添加或不存在
              </div>
            </el-cascader>
          </el-form-item>
          <el-form-item
            ref="studentIds"
            v-if="formSemester.schedulingType == 2"
            label="授课学员"
            prop="studentIds"
          >
            <el-cascader
              filterable
              collapse-tags
              class="param_ipt"
              v-model="formSemester.studentIds"
              placeholder="可搜索：分院/专业/班级/学生"
              :options="studentTeachingList"
              clearable
              :props="{
                multiple: true,
                label: 'name',
                value: 'id',
                children: 'children',
                disabled: 'disabled',
              }"
            >
              <div slot="empty" class="search_empty">
                搜索学生已添加或不存在
              </div>
            </el-cascader>
          </el-form-item>
          <div
            class="titleInfo"
            v-if="
              distribution.disciplineScorePercentage > 0 ||
              distribution.usualScorePercentage > 0 ||
              distribution.otherScorePercentage > 0 ||
              distribution.attendanceScorePercentage > 0
            "
          >
            平时分配置
          </div>
          <el-form-item
            v-if="
              courseInfo.courseType != 3 &&
              distribution.disciplineScorePercentage > 0
            "
            label="纪律初始分"
            prop="initialDisciplineScore"
            ref="initialDisciplineScore"
          >
            <el-input
              class="param_ipt"
              oninput="value=value.replace(/[^0-9]|^0+(?!$)/g,'');if(parseInt(value)>100) value='100';"
              style="width: 304px"
              placeholder="满分为100分"
              v-model="formSemester.initialDisciplineScore"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="课堂表现初始分"
            prop="initialUsualScore"
            ref="initialUsualScore"
            v-if="distribution.usualScorePercentage > 0"
          >
            <el-input
              class="param_ipt"
              oninput="value=value.replace(/[^0-9]|^0+(?!$)/g,'');if(parseInt(value)>100) value='100';"
              style="width: 304px"
              placeholder="满分为100分"
              v-model="formSemester.initialUsualScore"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            v-if="
              courseInfo.courseType != 3 &&
              distribution.otherScorePercentage > 0
            "
            label="其他初始分"
            prop="initialOtherScore"
            ref="initialOtherScore"
          >
            <el-input
              class="param_ipt"
              oninput="value=value.replace(/[^0-9]|^0+(?!$)/g,'');if(parseInt(value)>100) value='100';"
              style="width: 304px"
              placeholder="满分为100分"
              v-model="formSemester.initialOtherScore"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            ref="score"
            v-if="
              courseInfo.courseType != 3 &&
              distribution.attendanceScorePercentage > 0
            "
            label="考勤扣分配置"
            prop="all"
          >
            <template slot="label">
              <span
              >考勤扣分配置
                <el-tooltip class="item" effect="dark" placement="top">
                  <i
                    class="el-icon-question"
                    style="font-size: 16px; cursor: pointer"
                  ></i>
                  <div slot="content">
                    <div>考勤分满分100，根据“异常情况+异常次数”扣分</div>
                    <div>注：考勤未打卡不扣分，需教师调整考勤状态</div>
                  </div>
                </el-tooltip>
              </span>
            </template>
            <div class="flex categoryLine" ref="leaveScore">
              <div style="width: 73px">请假</div>
              <div class="flex">
                -
                <el-input
                  @focus="handleFocus($event, 'leaveScore')"
                  class="param_ipt ml10"
                  oninput="value=value.replace(/[^0-9]|^0+(?!$)/g,'');if(parseInt(value)>100) value='100';"
                  style="width: 80px; margin-right: 8px"
                  placeholder="请输入"
                  v-model="formSemester.leaveScore"
                >
                </el-input>
                分/次
              </div>
            </div>
            <div class="flex categoryLine" ref="absentScore">
              <div style="width: 73px">旷课</div>

              <div class="flex">
                -
                <el-input
                  @focus="handleFocus($event, 'absentScore')"
                  class="param_ipt ml10"
                  oninput="value=value.replace(/[^0-9]|^0+(?!$)/g,'');if(parseInt(value)>100) value='100';"
                  style="width: 80px; margin-right: 8px"
                  placeholder="请输入"
                  v-model="formSemester.absentScore"
                >
                </el-input>
                分/次
              </div>
            </div>
            <div class="flex categoryLine" ref="lateScore">
              <div style="width: 73px">迟到</div>
              <div class="flex">
                -
                <el-input
                  @focus="handleFocus($event, 'lateScore')"
                  class="param_ipt ml10"
                  oninput="value=value.replace(/[^0-9]|^0+(?!$)/g,'');if(parseInt(value)>100) value='100';"
                  style="width: 80px; margin-right: 8px"
                  placeholder="请输入"
                  v-model="formSemester.lateScore"
                >
                </el-input>
                分/次
              </div>
            </div>
            <div class="flex categoryLine" ref="leaveEarlyScore">
              <div style="width: 73px">早退</div>
              <div class="flex">
                -
                <el-input
                  @focus="handleFocus($event, 'leaveEarlyScore')"
                  class="param_ipt ml10"
                  oninput="value=value.replace(/[^0-9]|^0+(?!$)/g,'');if(parseInt(value)>100) value='100';"
                  style="width: 80px; margin-right: 8px"
                  placeholder="请输入"
                  v-model="formSemester.leaveEarlyScore"
                >
                </el-input>
                分/次
              </div>
            </div>
            <div class="flex categoryLine" ref="lateAndLeaveEarlyScore">
              <div style="width: 73px">迟到&早退</div>
              <div class="flex">
                -
                <el-input
                  @focus="handleFocus($event, 'lateAndLeaveEarlyScore')"
                  class="param_ipt ml10"
                  oninput="value=value.replace(/[^0-9]|^0+(?!$)/g,'');if(parseInt(value)>100) value='100';"
                  style="width: 80px; margin-right: 8px"
                  placeholder="请输入"
                  v-model="formSemester.lateAndLeaveEarlyScore"
                >
                </el-input>
                分/次
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="handleClose">取 消</el-button>
        <el-button
          v-preventReClick
          type="primary"
          @click="submitForm('semesterForm')"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
    <studyRecordConfirm
      ref="studyRecordConfirm"
      :courseName="courseInfo.courseName"
      :recoverList="recoverList"
      :openType="openType"
      @updateClass="updateForm"
      @addClass="resetConfirm"
    ></studyRecordConfirm>
  </div>
</template>
<!--TODO:改变逻辑！！！-->
<script>
import { getDistributionList, getRecoverStudyRecordList } from '@/api/course/course'
import {
  addCourseScheduling,
  checkTypeAndScore,
  getCourseTeacherList,
  getSchedulingClassList,
  getSchedulingStudentList,
  getTeacherUnMarkNum,
  updateCourseScheduling
} from '@/api/teach/teach'
import { listUser } from '@/api/system/user'
import { convertStudentArrayWithCustomNames, formatArrayWithCustomNames } from '../formatOrganizationData'
import studyRecordConfirm from '@/views/teachIndex/compontents/studyRecordConfirm.vue'

export default {
  name: 'addTeachingDialog',
  components: {
    studyRecordConfirm
    // classTeachingDialog
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    teachingDetial: {
      type: [Object],
      default: null
    },
    openType: {
      type: [String, Number],
      default: '1'
    },
    classTeachingId: {
      type: [String, Number],
      default: ''
    },
    courseInfo: {
      type: [Object],
      default: {
        courseId: '',
        courseName: '',
        courseType: ''
      }
    }
  },
  data() {
    return {
      title: '',
      oldJsonString: '',
      showCreateClass: false,
      addedUserId: [],
      instructorTeacherList: [],
      assistantList: [],
      classTeachingList: [],
      studentTeachingList: [],
      formSemester: {
        schoolId: this.$store.getters.schoolId,
        type: 0,
        classIds: [],
        classId: [],
        studentIds: [],
        teacherIds: [],
        assistantIds: [],
        schedulingType: 0,
        initialDisciplineScore: '',
        initialUsualScore: '',
        initialOtherScore: '',
        all: true,
        schedulingName: '',
        leaveScore: 0,
        absentScore: 0,
        lateScore: 0,
        leaveEarlyScore: 0,
        lateAndLeaveEarlyScore: 0
      },
      rules: {},
      distribution: {},
      recoverList: []
    }
  },
  watch: {
    dialogVisible: {
      async handler(val) {
        if (val) {
          this.$nextTick(async() => {
            this.resetForm('semesterForm')
            await this.FnGetDistributionList()
            await this.getCourseTeacherList()
            this.getListUser()
            this.getList()
            //编辑
            if (this.openType == 2) {
              this.formSemester = this.teachingDetial
              this.formSemester.all = true
              console.log('teachingDetial', this.teachingDetial)
              this.formSemester.teacherIds = this.teachingDetial.teacherIds
                .split(',')
                .map((item) => {
                  return item - 0
                })
              if (this.teachingDetial.assistantIds) {
                this.formSemester.assistantIds =
                  this.teachingDetial.assistantIds
                    .split(',')
                    .map((id) => id - 0)
              }
              this.formSemester.schedulingType =
                this.teachingDetial.schedulingType

              this.formSemester.leaveScore = this.teachingDetial.leaveScore
                ? this.teachingDetial.leaveScore
                : 0
              this.formSemester.absentScore = this.teachingDetial.absentScore
                ? this.teachingDetial.absentScore
                : 0
              this.formSemester.lateScore = this.teachingDetial.lateScore
                ? this.teachingDetial.lateScore
                : 0
              this.formSemester.leaveEarlyScore = this.teachingDetial
                .leaveEarlyScore
                ? this.teachingDetial.leaveEarlyScore
                : 0
              this.formSemester.lateAndLeaveEarlyScore = this.teachingDetial
                .lateAndLeaveEarlyScore
                ? this.teachingDetial.lateAndLeaveEarlyScore
                : 0

              this.formSemester.type = this.teachingDetial.type
              if (this.teachingDetial.schedulingType == 2) {
                this.formSemester.schedulingName =
                  this.teachingDetial.schedulingName
                this.oldJsonString = JSON.stringify(
                  this.teachingDetial.studentIdList
                )
                this.formSemester.studentIds =
                  this.teachingDetial.studentIdList
              } else if (this.teachingDetial.schedulingType == 1) {
                this.oldJsonString = JSON.stringify(
                  this.teachingDetial.classIdList
                )
                this.formSemester.classIds = this.teachingDetial.classIdList
              } else {
                this.oldJsonString = JSON.stringify(
                  this.teachingDetial.classIdList[0]
                )
                this.formSemester.classId = this.teachingDetial.classIdList[0]
              }
              console.log(this.formSemester)
            }
          })
        }
      }
    },
    'formSemester.teacherIds': {
      handler(val) {
        console.log('formSemester.teacherIds', val)
        this.$nextTick(() => {
          if (this.dialogVisible) {
            this.addedUserId = []
            for (const instructorTeacherListElement of this
              .instructorTeacherList) {
              if (val.includes(instructorTeacherListElement.teacherId)) {
                this.addedUserId.push(instructorTeacherListElement.userId)
              }
            }
          }
        })
      },
      deep: true,
      immediate: true
    },
    'formSemester.schedulingType': {
      handler(val) {
        this.updateRules(val)
        if (this.dialogVisible) {
          this.$nextTick(() => {
            this.$refs.semesterForm.clearValidate()
            this.getList()
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    checkClassIds() {
      let arr = []
      if (this.formSemester.schedulingType == 0) {
        arr.push(
          this.formSemester.classId[this.formSemester.classId.length - 1]
        )
      } else if (this.formSemester.schedulingType == 1) {
        arr = this.formSemester.classIds.map(
          (subArray) => subArray[subArray.length - 1]
        )
      }
      return arr
    },
    checkstudentIds() {
      let arr = []
      if (this.formSemester.schedulingType == 2) {
        arr = this.formSemester.studentIds.map(
          (subArray) => subArray[subArray.length - 1]
        )
      }
      return arr
    }
  },
  methods: {
    handleFocus(e, key) {
      if (e.detail == 0) {
        this.formSemester[key] = ''
      }
    },
    attendanceBlur(e, key) {
      if (
        this.formSemester[key] == null ||
        this.formSemester[key] == '' ||
        this.formSemester[key] == undefined
      ) {
        this.formSemester[key] = 0
      }
    },
    // 获取配分
    async FnGetDistributionList() {
      try {
        let res = await getDistributionList(this.courseInfo.courseId)
        if (res.code == 200) {
          this.distribution = res.data
        }
      } finally {
      }
    },
    updateRules(val) {
      const rules = {
        type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        initialDisciplineScore: [
          { required: true, message: '请输入纪律初始分', trigger: 'blur' }
        ],
        all: [{ required: true }],
        initialUsualScore: [
          { required: true, message: '请输入课堂表现初始分', trigger: 'blur' }
        ],
        initialOtherScore: [
          { required: true, message: '请输入其他初始分', trigger: 'blur' }
        ],
        teacherIds: [
          { required: true, message: '请选择授课教师', trigger: 'change' }
        ],
        schedulingType: [
          { required: true, message: '请选择班级类型', trigger: 'change' }
        ],
        schedulingName: [
          { required: true, message: '请输入拆班名称', trigger: 'blur' }
        ]
      }
      const schedulingTypeRules = {
        0: {
          classId: [
            { required: true, message: '请选择授课班级', trigger: 'change' }
          ]
        },
        1: {
          classIds: [
            { required: true, message: '请选择授课班级', trigger: 'change' }
          ]
        },
        2: {
          studentIds: [
            { required: true, message: '请选择授课班级', trigger: 'change' }
          ]
        }
      }
      this.rules = { ...rules, ...schedulingTypeRules[val] }
    },
    getList() {
      if (this.formSemester.schedulingType == 2) {
        this.getAllStudentList()
      } else {
        this.getAllClassList()
      }
    },
    addClassTeaching() {
      this.title = '创建授课班级'
      this.showCreateClass = true
    },
    submitForm(formName) {
      this.$refs[formName].validate(async(valid, fields) => {
        console.log(fields)
        for (const key in fields) {
          console.log(fields[key][0].field)
          let label = fields[key][0].field
          if (
            this.formSemester[label] == null ||
            this.formSemester[label] == ''
          ) {
            this.$refs[label].$el.scrollIntoView({
              behavior: 'smooth',
              block: 'center'
            })
            return
          }
        }
        if (valid) {
          if (
            this.formSemester.schedulingType == 1 &&
            this.formSemester.classIds.length < 2
          ) {
            this.$modal.msgWarning('合班班级至少为两个班')
            return
          }
          if (
            this.courseInfo.courseType != 3 &&
            this.distribution.attendanceScorePercentage > 0
          ) {
            console.log(this.$refs)
            if (this.formSemester.leaveScore === '') {
              this.$modal.msgWarning('请完善考勤扣分配置')
              this.$refs['score'].$el.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
              })
              return
            }
            if (this.formSemester.absentScore === '') {
              this.$modal.msgWarning('请完善考勤扣分配置')
              this.$refs['score'].$el.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
              })
              return
            }
            if (this.formSemester.lateScore === '') {
              this.$modal.msgWarning('请完善考勤扣分配置')
              this.$refs['score'].$el.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
              })
              return
            }
            if (this.formSemester.leaveEarlyScore === '') {
              this.$modal.msgWarning('请完善考勤扣分配置')
              this.$refs['score'].$el.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
              })
              return
            }
            if (this.formSemester.lateAndLeaveEarlyScore === '') {
              this.$modal.msgWarning('请完善考勤扣分配置')
              this.$refs['score'].$el.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
              })
              return
            }
          }

          let params = {
            ...this.formSemester,
            teacherIds:
              this.formSemester.teacherIds.length > 0
                ? this.formSemester.teacherIds.join(',')
                : '',
            assistantIds:
              this.formSemester.assistantIds &&
              this.formSemester.assistantIds.length > 0
                ? this.formSemester.assistantIds.join(',')
                : '',
            courseId: this.courseInfo.courseId,
            classIds: null,
            studentIds: null,
            semesterId: this.courseInfo.semesterId
          }
          if (this.formSemester.schedulingType == 2) {
            let studentIds = this.formSemester.studentIds.map(
              (subArray) => subArray[subArray.length - 1]
            )
            params.studentIds = studentIds.join(',')
          } else if (this.formSemester.schedulingType == 1) {
            let classIds = this.formSemester.classIds.map(
              (subArray) => subArray[subArray.length - 1]
            )
            params.classIds = classIds.join(',')
          } else {
            params.classIds =
              this.formSemester.classId[this.formSemester.classId.length - 1]
          }

          if (this.openType == 2) {
            let query = {
              teacherIds: this.teachingDetial.teacherIds - 0,
              courseSchedulingId: this.classTeachingId
            }
            const loading = this.$loading({
              lock: true,
              text: '正在检查未批改考核/作业数量...',
              spinner: 'el-icon-loading',
              background: 'rgba(255, 255, 255, 0.3)'
            })
            let need = 0
            try {
              console.log(this.teachingDetial.teacherIds, params.teacherIds)
              let oldArr = this.teachingDetial.teacherIds.map((id) => id - 0)
              let newArr = this.formSemester.teacherIds.sort()
              for (const newArrElement of newArr) {
                if (oldArr.includes(newArrElement)) {
                  need++
                }
              }
              query.teacherIds = this.teachingDetial.teacherIds.join(',')
              let state = await getTeacherUnMarkNum(query)
              if (state.data.teacherUnMarkNum > 0 && need == 0) {
                this.$confirm(state.data.warnContent, '编辑失败', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                })
                  .then(() => {
                  })
                  .catch(() => {
                  })
                return
              }
            } catch (e) {
              console.error(e)
            } finally {
              loading.close()
            }
            params.id = this.teachingDetial.schedulingId
          }
          // 获取可恢复学生记录
          try {
            let obj = {
              courseId: this.courseInfo.courseId,
              classIds: this.checkClassIds.join(','),
              studentIds: this.checkstudentIds.join(',')
            }
            let res = await getRecoverStudyRecordList(obj)
            if (res.code == 200) {
              this.recoverList = res.data
              // 有可恢复学生记录
              if (this.recoverList && this.recoverList.length > 0) {
                this.$refs.studyRecordConfirm.show(params)
              } else {
                params.recoverStudyRecord = 0
                if (this.openType == 2) {
                  this.updateForm(params)
                } else {
                  this.resetConfirm(params)
                }
              }
            }
          } catch (err) {
            console.log(err)
          }
        } else {
          return false
        }
      })
    },
    async resetConfirm(params) {
      const loading = this.$loading({
        lock: true,
        text: `正在添加...`,
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.3)'
      })
      try {
        let res = await addCourseScheduling(params)
        const { code } = res
        if (code == 200) {
          loading.close()
          this.$modal.msgSuccess('添加成功')
          this.handleClose()
          this.$emit('refresh', true)
        } else {
          loading.close()
        }
      } catch (e) {
        loading.close()
      }
    },
    async updateForm(params) {
      const loading = this.$loading({
        lock: true,
        text: `正在编辑...`,
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.3)'
      })
      try {
        let res = await updateCourseScheduling({
          ...params,
          id: this.classTeachingId
        })
        const { code } = res
        if (code == 200) {
          loading.close()
          this.$modal.msgSuccess('编辑成功')
          this.handleClose()
          this.$emit('refresh', true)
        } else {
          loading.close()
        }
      } catch (e) {
        loading.close()
      }
    },
    // 跨学期校验
    async confirmBefore(data) {
      let res = await checkTypeAndScore(data)
      if (res.code == 200) {
        if (res.data == 0) {
          this.resetConfirm()
        } else {
          this.$confirm(
            `该课程为跨学期课程，当前设置的${
              this.courseInfo.courseType !== 3
                ? '课程类型'
                : res.data === 1
                  ? '课程类型及初始分'
                  : res.data === 2
                    ? '课程类型'
                    : '初始分'
            }与其他学期排课配置不一致，是否确定更新，确定后会同步更新其他学期排课配置？`,
            '排课确认',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(async() => {
            this.resetConfirm()
          })
        }
      }
    },

    async getCourseTeacherList() {
      try {
        let params = {
          courseId: this.courseInfo.courseId
        }
        let res = await getCourseTeacherList(params)
        const { code, data } = res
        if (code === 200) {
          this.instructorTeacherList = data
          if (this.$store.getters.roleId == 'teacher' && this.openType == 1) {
            console.log(
              'this.$store.getters',
              this.$store.getters,
              this.$store.getters.teacherId
            )
            this.formSemester.teacherIds = [this.$store.getters.teacherId]
            console.log(this.formSemester.teacherIds)
          }
        }
      } catch (e) {
        console.error(e)
      }
    },
    async getListUser() {
      try {
        let params = {
          status: 0,
          pageNum: 1,
          pageSize: 999999,
          schoolId: this.$store.getters.schoolId
        }
        let res = await listUser(params)
        const { code, rows } = res
        if (code === 200) {
          rows.forEach((item) => {
            item.labelName = `${item.nickName}(${item.userName.slice(2)})`
          })
          this.assistantList = rows
        }
      } catch (e) {
        console.error(e)
      }
    },
    async getAllClassList() {
      try {
        let params = {
          courseId: this.courseInfo.courseId,
          courseSchedulingId: this.openType == 2 ? this.classTeachingId : 0,
        };
        let res = await getSchedulingClassList(params);
        const { code, data } = res;
        if (code === 200) {
          this.classTeachingList = formatArrayWithCustomNames(data)
        }
      } catch (e) {
        console.error(e)
      }
    },
    async getAllStudentList() {
      try {
        let params = {
          courseId: this.courseInfo.courseId
        }
        let res = await getSchedulingStudentList(params)
        const { code, data } = res
        if (code === 200) {
          this.studentTeachingList = convertStudentArrayWithCustomNames(data, true)
        }
      } catch (e) {
        console.error(e)
      }
    },
    handleClose() {
      this.$emit('update:dialogVisible', false)
    },
    resetForm() {
      this.formSemester = {
        ...this.formSemester,
        classIds: [],
        classId: [],
        studentIds: [],
        teacherIds: [],
        assistantIds: [],
        schedulingType: 0,
        initialUsualScore: '',
        initialDisciplineScore: '',
        initialOtherScore: '',
        leaveScore: 0,
        absentScore: 0,
        lateScore: 0,
        leaveEarlyScore: 0,
        lateAndLeaveEarlyScore: 0,
        schedulingName: ''
      }
    },
    clearFormValidation() {
      this.$refs.semesterForm.clearValidate()
    },
    handleBlur() {
      this.formSemester.schedulingName =
        this.formSemester.schedulingName.trim()
      this.$refs.semesterForm.validateField('schedulingName')
    }
  }
}
</script>

<style scoped lang="scss">
.categoryLine {
  margin-bottom: 15px;
}

// 滚动条去除
.form::-webkit-scrollbar {
  // display: none;
}

.form {
  max-height: calc(100vh - 260px);
  overflow-y: auto;

  .course_name {
    color: #11a983;
    display: flex;
    font-size: 18px;
  }

  .title {
    font-size: 16px;
    font-weight: bold;
    margin-top: 10px;
    margin-bottom: 10px;
  }

  .titleInfo {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
  }

  .param_ipt {
    width: 304px;
  }
}

.sign {
  color: #ff9724;
  font-size: 14px;
}

.ml10 {
  margin-left: 8px;
}
</style>
